<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/6
 * Time: 17:47
 */

namespace App\Model\Backstage;


use App\Model\Base;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Session;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;


class User extends Model
{
    protected $table;
    protected $request;

    public function __construct()
    {
        $this->table = 'user';
    }

    /**
     * 根据员工ID 获取员工类型
     * @param $uId
     * @return mixed
     */
    public  function getUserType()
    {
        $type = DB::table('user')->where('u_id', $this->uid)->value('u_type');
        return ['type' => $type, 'uid' => $this->uid];
    }

    /**
     * @param array $map
     * @return mixed
     * 获取用户列表
     */
    public function getUserList ($map = [], $pageLimit)
    {
        $list = DB::table('user')
            ->leftJoin('staff', 'u_id', '=', 'area_manager_id')
            ->leftJoin('department', 'u_d_id', '=', 'department.id')
            ->where($map)
            ->select('u_id', 'u_d_id', 'name', 'u_username', 'u_account_number', 'u_last_ip',
                DB::raw('from_unixtime(u_last_time) AS u_last_time'),'u_status',
                DB::raw('from_unixtime(h_user.created_at) AS created_at'),DB::raw('from_unixtime(h_user.updated_at) AS updated_at'),
                'sex', 'birthday', 'jiguan', 'nation', 'college', 'political_face', 'speciality', 'record_type', 'people_num',
                'phone', 'email', 'staff.address', 'bank_num', 'bank_remark', 'personal_profile', 'post',
                DB::raw('from_unixtime(entry_time) AS entry_time'),DB::raw('from_unixtime(separation_time) AS separation_time'),
                'source', 'remark')
            ->orderBy('u_id', 'desc')
            ->paginate($pageLimit);
        if (sizeof($list) == 0) {
            return false;
        }
        return $list;


    }


    /**
     * @param $params
     * @return mixed
     * 添加中介公司用户
     */
    public function addUser ($params)
    {
        $time = time();
        $params['created_at'] =  $time;
        //开启事务
        DB::beginTransaction();
        $uid = $this->insertGetId([
            'u_b_id'           =>  $params['u_b_id'],
            'u_d_id'           =>  $params['u_d_id'],
            'u_username'       =>  $params['u_username'],
            'u_account_number' =>  $params['u_account_number'],
            'u_password'       =>  Hash::make($params['u_password']),
            'u_type'           =>  1,
            'u_status'         =>  1,
            'created_at'       =>  $time,
            'updated_at'       =>  $time,
            'is_del'           =>  0
        ]);
        $sid = DB::table('staff')->insertGetId([
            'branch_id'       =>  $params['u_b_id'],
            'area_manager_id' =>  $uid,
            'sex'             =>  $params['sex'],
            'birthday'        =>  $params['birthday'],
            'jiguan'          =>  $params['jiguan'],
            'nation'          =>  $params['nation'],
            'college'         =>  $params['college'],
            'political_face'  =>  $params['political_face'],
            'speciality'      =>  $params['speciality'],
            'record_type'     =>  $params['record_type'],
            'people_num'      =>  $params['people_num'],
            'phone'           =>  $params['phone'],
            'email'           =>  $params['email'],
            'address'         =>  $params['address'],
            'bank_num'        =>  $params['bank_num'],
            'bank_remark'     =>  $params['bank_remark'],
            'personal_profile'=>  $params['personal_profile'],
            'post'            =>  $params['post'],
            'entry_time'      =>  $time,
            'source'          =>  $params['source'],
            'remark'          =>  $params['remark']
        ]);
        if ($uid && $sid) {
            DB::commit();
            return true;

        } else {
            DB::rollback();
            return false;
        }

    }


    /**
     * @param $map
     * @param $params
     * @return mixed
     * 修改中介公司用户信息
     */
    public function saveUser ($params)
    {
        $time = time();
        //开启事务
        DB::beginTransaction();
        $uid = $this->where('u_id',$params['u_id'])->update([
            'u_d_id'           =>  $params['u_d_id'],
            'u_username'       =>  $params['u_username'],
            'updated_at'       =>  $time,
            'u_status'         =>  $params['u_status']
        ]);
        $sid = DB::table('staff')->where('area_manager_id', $params['u_id'])->update([
            'sex'             =>  $params['sex'],
            'birthday'        =>  $params['birthday'],
            'jiguan'          =>  $params['jiguan'],
            'nation'          =>  $params['nation'],
            'college'         =>  $params['college'],
            'political_face'  =>  $params['political_face'],
            'speciality'      =>  $params['speciality'],
            'record_type'     =>  $params['record_type'],
            'people_num'      =>  $params['people_num'],
            'phone'           =>  $params['phone'],
            'email'           =>  $params['email'],
            'address'         =>  $params['address'],
            'bank_num'        =>  $params['bank_num'],
            'bank_remark'     =>  $params['bank_remark'],
            'personal_profile'=>  $params['personal_profile'],
            'post'            =>  $params['post'],
            'source'          =>  $params['source'],
            'remark'          =>  $params['remark'],
            's_update_time'   =>  $time
        ]);
        if ($uid && $sid) {
            DB::commit();
            return true;

        } else {
            DB::rollback();
            return false;
        }
    }

    /**
     * @param $uid
     * @return mixed
     * 删除中介公司用户信息
     */
    public function delUser($uid)
    {
        return $this->where(['u_id' => $uid])->update(['is_del' => 1]);
    }

    /**上级重置员工密码
     * @param $uid 员工ID
     * @return mixed
     */
    public static function resetPassword($uid)
    {
        return DB::table('user')->where('u_id', $uid)->update(['u_password' => Hash::make(123456), 'updated_at' => time()]);
    }

    /**修改密码
     * @param $newPassword
     * @return mixed
     */
    public static function updatePassword($newPassword)
    {
        $uId = Auth::user()->u_id;
        return DB::table('user')->where('u_id', $uId)->update([
            'u_password'     => Hash::make($newPassword),
            'updated_at'               => time()
        ]);
    }

    /**
     * @param $params
     * @return bool|string
     * 用户登陆
     */
    public function loginUser ($params)
    {
        $user_info = User::where('u_account_number', $params['u_account_number'])->first();
        if (!$user_info) {
            return -4;//账号不存在
        }
        if ($user_info->u_status == 2) {
            return -5;//账号被禁用
        }
        if ($user_info->is_del == 1) {
            return -6;//账号被管理者删除
        }
        // 判断密码是否正确
        if (Hash::check($params['u_password'], $user_info->u_password)){
            //查询该账号所属的公司状态
            $status = DB::table('account_number_manager')->where('anm_id', $user_info->u_b_id)->value('anm_status');

            if ($status == 2) {
                //公司还在审核中不能登录
                return -1;
            } elseif ($status == 3) {
                //公司账号到期没有续费无法登录
                 return -2;
            } elseif($status == 1) {
                // 生成随机字符串存数据库 用户认证用
                $apiToken = str_random(60);
                $data['u_api_token'] = $apiToken;
                $data['u_last_time'] = time();
                $data['u_last_ip'] = $_SERVER["REMOTE_ADDR"];
                $this->where(['u_id'=>$user_info->u_id])->update($data);
                unset($user_info['u_password']);
                return $apiToken;
            }else {
                //未知状态 请联系管理员
                return -3;
            }

        }else{
            return false;
        }
    }
}